<?php

namespace traits;

use app\exception\BaseException;

trait FileTrait
{
    // 创建压缩包
    public function creatZipFile($filename,$files = null)
    {
        $zipArchive =  new \ZipArchive();
        $zipArchive -> open($filename,\ZipArchive::CREATE);
        if(empty($files)){
            $zipArchive -> addEmptyDir(str_replace('.zip','',basename($filename)));
        }else{
            if(is_array($files)){
                foreach ($files as $file){
                    if(is_file($file)){
                        $zipArchive -> addFile($file,basename($file));
                    }
                }
            }else{
                $zipArchive -> addFile($files,basename($files));
            }
        }
        $zipArchive -> close();
        return $filename;
    }

    // 创建文件
    public function createFile($filename,$size = null)
    {
        $path = dirname($filename);
        if(!file_exists($path)){
            mkdir($path,0755,true);
        }
        if(!file_exists($filename)){
            touch($filename,0755);
        }
        if(!empty($size)){
            $fileInfo = explode('.',basename($filename));
            $basename = array_shift($fileInfo);
            $files = $this->scanDir("$path/$basename*");
            $lastFile = $path . '/' .end($files);
            if(file_exists($filename) && filesize($lastFile) > $size){
                $extension = implode('.',$fileInfo);
                $filename = $path . '/' . $basename . '_' . time() . '.' . $extension;
                touch($filename,0755);
            }
        }
        return $filename;
    }

    /**
     * 生成目录
     * @param $pathname
     * @return void
     */
    public function createPath($pathname)
    {
        if(file_exists($pathname)){
            return ;
        }
        mkdir($pathname,0755,true);
    }

    /**
     * 扫描路径下的文件
     * @return array
     */
    public function scanDir($pattern, $flags = null): array
    {
        $files = glob($pattern, $flags);
        if (empty($files)) {
            $files = [];
        } else {
            $files = array_map('basename', $files);
        }
        return $files;
    }

    /**
     * 扫描路径下所有文件包括子目录
     * @param $dir
     * @return array
     */
    public function scanSubDir($dir): array
    {
        $dirs = [];
        $subDirs = $this->scanDir("$dir/*", GLOB_ONLYDIR);
        if (!empty($subDirs)) {
            foreach ($subDirs as $subDir) {
                $subDir = "$dir/$subDir";
                $dirs[] = $subDir;
                $subDirSubDirs = $this -> scanSubDir($subDir);
                if (!empty($subDirSubDirs)) {
                    $dirs = array_merge($dirs, $subDirSubDirs);
                }
            }
        }
        return $dirs;
    }

    /**
     * 获取上传的excel数据，没有合并单元格的数据
     * @param $file
     * @param $headField
     * @param $readLine int 从第几行开始取表头和数据
     * @return array
     */
    public function getUploadFileData($file, $headField, int $readLine = 2)
    {
        if (empty($file['tmp_name'])) {
            throw new BaseException(lang('上传文件有误'), -10);
        }
        $ext = strtolower(strrchr($file['name'], '.'));
        if ($ext != '.xlsx') {
            throw new BaseException(lang('上传文件类型有误'), -11);
        }
        //缓存路径
        $temp_file = sys_get_temp_dir();
        $excel = new \Vtiful\Kernel\Excel(['path' => $temp_file]);

        $file['tmp_name'] = str_replace('\\','/',$file['tmp_name']);
        $tmpName = strrchr($file['tmp_name'], '/');

        // 读取文件
        $sheetList = $excel->openFile($tmpName)
            ->sheetList();
        if (empty($sheetList)) {
            throw new BaseException(lang('上传文件内容为空'), -12);
        }
        $sheetData = $excel
            ->openSheet($sheetList[0])
            ->setType([
                0 => \Vtiful\Kernel\Excel::TYPE_STRING
            ])
            ->getSheetData();

        if (!isset($sheetData[0]) || !isset($sheetData[1]) || !isset($sheetData[$readLine])) {
            throw new BaseException(lang('上传文件内容为空'), -13);
        }
        $fieldLocation = array();
        foreach ($sheetData[1] as $key => $value) {
            $fieldLocation[$value] = $key;
        }

        for ($i = 0; $i < $readLine; $i++) {
            unset($sheetData[$i]);
        }
        $needNew = [];
        foreach ($headField as $key => $value) {
            if (!isset($fieldLocation[$value])) {
                throw new BaseException(lang('缺少必要列：') . $value, -14);
            }
            $needNew[$value] = $fieldLocation[$value];
        }

        return [$needNew, $sheetData];
    }
}